package com.bbs.toutiao.config;


import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.bbs.toutiao.entity.UserEntity;
import com.bbs.toutiao.mapper.admin.UserMapper;
import com.bbs.toutiao.service.admin.impl.UserServiceImpl;
import com.bbs.toutiao.utils.Jwt;
import com.bbs.toutiao.vo.user.UpdateStatusVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 描述: jwt拦截器
 * 作者： zhangBin
 * 时间： 2023/9/17 14:29
 * 版本： 1.0
 */
@Slf4j
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    UserMapper userMapper;


    static Long NEX = 150000L;//剩余两天则续约
    static Cache<Object, Object> cache = CacheUtil.newLFUCache(1000, 120 * 1000);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String apiUrl = request.getRequestURI();
        log.info("访问类型为:" + request.getMethod() + "访问接口为:" + apiUrl);
        //获取token
        String token = request.getHeader("token");
            if (Jwt.verify(token)) {
                final JWT jwt = JWTUtil.parseToken(token);
                long exp = Long.parseLong(jwt.getPayload("exp").toString());//到期时间
                long cur = DateUtil.currentSeconds();  //获取当前时间戳
                UserEntity userEntity;
                Integer userId = Integer.valueOf(jwt.getPayload("userId").toString());
                userEntity = userMapper.getUserTimeById(userId);
                banCheck(userEntity);
                if (exp - cur <= NEX) { //判断是否续约
                    log.info("token续约");
                    String tokens = Jwt.getToken(userEntity);
                    response.setHeader("token", tokens);
                    return true;
                }
                return true;
            }
        return false;
    }

    /**
     * 用户状态检查
     * 1.封禁七天
     * 2.封禁
     *
     * @param user
     */
    public void banCheck(UserEntity user) {
        UpdateStatusVo statusVo = new UpdateStatusVo();
        Integer status = user.getStatus();
        long cur = DateUtil.currentSeconds();  //获取当前时间戳
//        log.info("用户状态为: " + status);
        UserServiceImpl.userStatus(statusVo, cur, user, status, userMapper, log);
    }
}



